package net.xuzhen97.distributed.transaction.course.service.executor;

import cn.hutool.core.util.IdUtil;
import net.xuzhen97.distributed.transaction.course.dao.UserCourse;
import net.xuzhen97.distributed.transaction.course.dao.UserCourseRepository;
import net.xuzhen97.distributed.transaction.course.service.dto.OpenCourseCmd;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
public class OpenCourseCmdExe {

    private final UserCourseRepository userCourseRepository;

    @Autowired
    public OpenCourseCmdExe(UserCourseRepository userCourseRepository){
        this.userCourseRepository = userCourseRepository;
    }

    /**
     * 开通课程执行逻辑， 开启事务保证检索数据从主库检索，避免读写延迟问题
     * @param cmd
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public String execute(OpenCourseCmd cmd){
        cmd.validate();
        // 先查询关系是否存在，存在则不处理，不存在处理，来保证幂等性
        UserCourse userCourse = userCourseRepository.getByUserIdAndCourseId(cmd.getUserId(), cmd.getCourseId());
        if(userCourse == null) {
            String id = IdUtil.getSnowflakeNextIdStr();
            userCourse = new UserCourse();
            userCourse.setId(id);
            userCourse.setUserId(cmd.getUserId());
            userCourse.setCourseId(cmd.getCourseId());
            userCourse.setCreatedBy(cmd.getOpUserId());
            userCourse.setCreatedDate(LocalDateTime.now());
            userCourseRepository.save(userCourse);
            return id;
        }
        return userCourse.getId();
    }
}
